<?php
/**
 * 中云通 游戏SKD通讯接口.
 * User: Kenny.Hu
 * Date: 2016/3/9
 * Time: 8:48
 */

namespace Zyt;


class SDK
{
    public $gateway;
    public $key;
    private $post_data;

    /**
     * 构造函数
     */
    public function __construct(){
        $this->gateway = '';
        $this->key     = '';
    }

    /**
     * 初始化并执行
     *
     * @param $parameters
     * @return mixed
     */
    public function start($parameters){
        $this->post_data = $parameters;
        $this->_exception();
        $data = $this->_buildRequestParam($this->post_data);
        $response = $this->_curl($this->gateway, $data);
        return $response;
    }

    /**
     * 抛出错误
     */
    private function _exception(){
        if( ! $this->gateway || ! $this->key )                        exit('网关或者Key配置错误');
        if( ! is_array($this->post_data) || empty($this->post_data) ) exit('参数列表错误');
    }

    /**
     * 生成要请求参数数组
     *
     * @param $params
     * @return mixed
     */
    private function _buildRequestParam($params){
        //除去待签名参数数组中的空值和签名参数
        $para_filter = $this->_paraFilter($params);
        //对待签名参数数组排序
        $para_sort = $this->_argSort($para_filter);
        //生成签名结果
        $mysign = $this->_buildRequestMysign($para_sort);
        //签名结果与签名方式加入请求提交参数组中
        $para_sort['sign'] = $mysign;
        return $para_sort;
    }

    /**
     * 请求参数过滤
     *
     * @param $para
     * @return array
     */
    private function _paraFilter($para) {
        $para_filter = array();
        foreach( $para as $key => $val ){
            if($key == "sign" || $key == "sign_type" || $val == "") continue;
            else	$para_filter[$key] = $para[$key];
        }
        return $para_filter;
    }

    /**
     * 请求参数重新排序
     *
     * @param $para
     * @return mixed
     */
    private function _argSort($para) {
        ksort($para);
        reset($para);
        return $para;
    }

    /**
     * 生成签名结果
     *
     * @param $para_sort
     * @return string
     */
    private function _buildRequestMysign($para_sort) {
        //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        $para_str = http_build_query($para_sort);
        $sign = $this->_md5Sign($para_str);
        return $sign;
    }

    /**
     * 签名字符串
     *
     * @param $para_str
     * @return string
     */
    private function _md5Sign($para_str){
        $para_str .= $this->key;
        return md5($para_str);
    }

    /**
     * 远程调用 - CURL_POST方式
     *
     * @param $url
     * @param $data
     * @return mixed
     */
    private function _curl($url, $data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        if(is_array($data) && ! empty($data)) curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}